package grpc

import (
	"context"
	"fmt"
	"gitee.com/qzcsu/go-web-study/client"
	"gitee.com/qzcsu/go-web-study/grpc/proto/pandago"
	"gitee.com/qzcsu/go-web-study/utils/jsonutil"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"log"
	"net/http"
	"time"
)

type AccessParam struct {
	SvrName string
	Param   string
}

func NotifyHello(c *gin.Context) {
	ctx := context.Background()
	param := &AccessParam{}
	// c.ShouldBind 使用了 c.Request.Body，不可重用。
	if errA := c.ShouldBind(&param); errA != nil {
		log.Printf("param bind err:%v\n", errA)
		c.JSON(http.StatusOK, gin.H{"message": "param bind err"})
		return
	}

	log.Printf("NotifyHello param:%+v \n", param)
	svrNode, err := client.GetGrpcSvrCli(param.SvrName)
	if err != nil {
		log.Printf("get grpc cli err: %v\n", err)
		c.JSON(http.StatusOK, gin.H{"message": "grpc cli err"})
		return
	}
	conn, err := grpc.Dial(fmt.Sprintf("%v:%v", svrNode.IpAddr, svrNode.Port), grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		log.Printf("did not connect: %v\n", err)
		c.JSON(http.StatusOK, gin.H{"message": "success"})
		return
	}
	defer conn.Close()
	grpcCli := pandago.NewPandaGoServiceClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	req := &pandago.HelloRequest{}
	jsonutil.JSONToStruct(param.Param, req)
	log.Printf("grpc invoker param=>[%+v]\n", req)
	resp, err := grpcCli.SayHello(ctx, req)
	if err != nil {
		log.Fatalf("could not SayHello: %v", err)
	}
	log.Printf("grpc resp:%+v\n", resp)
	c.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})
}
